<?php 
class IndexControl extends Control{
	//首页
	public function  index(){
		$this->common();
		// p($db);
		$this->display('index.html');


	}
	
	//栏目页
	//===============================1===========================
	public function category(){ 

		//树形导航
		$this->common();
		$cid = Q('cid',0,'intval');
		$categoryCache= cache('category');
		//验证栏目 如果没有这个栏目就跳转到首页
		if(!isset($categoryCache[$cid])){
			go(__ROOT__);
		}
		//如果参数没有attr变量生成此变量
		if(!Q('get.s')){
			//商品类型id
			$gtid = $categoryCache[$cid]['gtid'];
			//获得属性的条数
			$attrNum=M('attr_class')->where(array('gtid'=>$gtid))->count();
			// p($attrNum);exit;
			//转换成可执行的0-9格式
			$attr='';
			for($i=0;$i<$attrNum;$i++){
				$attr.='0-';
			}
			$attr=substr($attr,0,-1);
			//没有get参数就跳转
			go(U('category',array('cid'=>$cid,'s'=>$attr)));
		}
		//分配商品列表
		//=================2=====================================
		$this->assignGoods($cid);
		//分配搜索属性
		//===============3============================================
		$this->assignSearchAttr($cid);
		//最近浏览
		if(isset($_SESSION['browse'])){
			$browse=$_SESSION['browse'];
			$lbrowse=array();
			foreach ($browse as $v) {
			$lbrowse[]=M('goods')->find("gid=$v");
		}
			$this->assign('browse',$lbrowse);
		}
		
		// foreach($borwse as )
		$this->assign('cid',$cid);
		//分级
        $partant=Data::parentChannel($categoryCache,$cid);
        $db=array_reverse($partant,true);
        //上级栏目上级栏目id
    	$name=$db[1]['cname'];
        $pid=$db[1]['cid'];
        $cate=M('goods')->where(array("cid"=>$cid))->limit(2)->all();
        $cc=M('goods')->where(array("cid"=>$cid))->limit(3)->all();
        $this->assign('cate',$cate);
     	$this->assign('name',$name);
      	$this->assign('cc',$cc);
     	$this->assign('pid',$pid);
     	$this->assign('db',$db);
		$this->display('goods_list.html');
		
	} 


	//分配商品
	public function assignGoods($cid){
		//获得参数s（0-0）
		$s=explode('-', Q('s'));
		//移除值为零的属性
		$searchAttr=array();
		foreach($s as $i => $d){
			if($d==0)continue;
			$searchAttr[]=$d;
		}
		//如果没值，就分配栏目下所有数据 
		if(empty($searchAttr)){
			//商品的数量
			$count=M('goods')->where("cid=$cid")->count();
			//分页
			$page=new Page($count,20);
			$goods=M('goods')->where("cid=$cid")->limit($page->limit())->all();
		}else{
			//========================4=====================
			//组合商品属性表自连接（用于检索）DB_PREFIX是hd_g_表前缀
			$table=C('DB_PREFIX').'goods_attr';
			$JOIN='';
			foreach($searchAttr as $i=>$avid){
				$as=' a'.$i;//表别名
				$JOIN.=$table.' AS '.$as.' JOIN ';
			}
			$JOIN=substr($JOIN,0,-5);
			//组合ON
			$ON=' ON ';
			for($i=0;$i<count($searchAttr)-1;$i++){
				$as=' a'.$i;//表别名
				$rAs=' a'.($i+1);//关联表
				$ON.=$as.'.gid='.$rAs.'.gid AND ';
			}
			$ON=$ON.' g.gid='.$as.'.gid';
			//组合where条件
			$WHERE=' WHERE ';
			foreach ($searchAttr as $i => $avid) {
				$as = ' a'.$i;//表别名
				$WHERE.=$as.'.avid='.$avid.' AND ';
			}
			$WHERE=$WHERE." g.cid=$cid";
			//获得商品总页数用于分页
			$CountSql="SELECT count(*) AS c FROM hd_g_goods AS g JOIN ".$JOIN.$ON.$WHERE;
			$COUNT=M()->query($CountSql);
			$page=new page($COUNT[0]['c'],20);
			$SQL = "SELECT * FROM hd_g_goods AS g JOIN ".$JOIN.$ON.$WHERE .' LIMIT '.$page->limit(true);
			$goods=M()->query($SQL);
		}
		//分配商品


		$this->assign('goods',$goods);
		//分配分页显示
		$this->assign('page',$page->show());
	}
	//分配搜索属性
	public function assignSearchAttr($cid){
		//栏目缓存数据
		$categoryCache=cache('category');
		//类型缓存数据
		$goodsType=cache('goodstype');
		//找到商品类型id
		$gtid=$categoryCache[$cid]['gtid'];
		//提取属性数据
		$attrClass=M('attr_class')->where(array('gtid'=>$gtid))->all();
		//添加attrvalue属性值， 到属性数据中
		foreach($attrClass as $n =>$class){
			$attrClass[$n]['attrvalue']=M("attr_value")->all("acid={$class['acid']}");
		}
		//分配搜索属性
		// p($attrClass);exit;
		$this->assign("attr",$attrClass);
	}

	//内容页
	public function content(){
		// $cid=Q('cid',0,'intval');
		//树形导航
		$this->common();
		// 接受商品的id
		$gid=Q('gid',0,'intval');
		//顾客最近浏览
		$this->browse($gid);
		//栏目id
		$cid=M('goods')->where("gid=$gid")->getField('cid');
		//栏目缓存
		$categoryCache=cache('category');
		//商品类型缓存
		$goodsType=cache('goodstype');
		//查找gtid
		$goodsModel=M('goods');
		$goods=$goodsModel->find($gid);
		$gtid=$categoryCache[$goods['cid']]['gtid'];
		//找到商品的是属性 （规格的）
		$attrClass=M('attr_class')->where("is_spec=1")->all("gtid=$gtid");
		//表前缀
		$pre=C("DB_PREFIX");
		foreach($attrClass as $n=>$class){
			$sql = "SELECT ga.value,ga.avid FROM {$pre}goods_attr AS ga JOIN {$pre}attr_value AS av ON ga.avid=av.avid WHERE ga.gid={$gid} AND av.acid={$class['acid']}";
			
			$attrClass[$n]['_attr']=M()->query($sql);
		}
		//获取库存
		$avid = Q("avid");
		// echo $avid;、
		if($avid){
			$avid =explode('_', $avid);
			$stid = $this->getStockId($gid,$avid);
			if($stid){
				$stock =M('stock')->where("gid=$gid")->find($stid);
				$currentAttr=$avid;
			}
		}else{
			//给个默认选中
			$stock=M('stock')->where("gid=$gid")->find();
			$currentAttr=M('stock_attr')->where("stid={$stock['stid']}")->getField('avid',true);
			// p($currentAttr);
		}
		//商品属性值
		// $goodsattr=M('goods_attr')->field('value')->where("gid=$gid")->all();
		// $this->assign('attr',$goodsattr);
		// p($goodsattr);
		//合并有库存里的值
		$goods=array_merge($goods,$stock);
		//图片路径
		$goodsPic=M('goods_pic')->all("gid=$gid");
		// p($goodsPic);exit;
		$this->assign('pic',$goodsPic);
		//图片的属性值M 红色  等
		$attrValue=M('attr_value')->where($currentAttr)->getField('attr_value',true);
		//留言
		$this->leave($gid);
		// p($attrValue);
		$partant=Data::parentChannel($categoryCache,$cid);
        $db=array_reverse($partant,true);
     
     	$this->assign('db',$db);
		$this->assign('av',$attrValue);
		$this->assign('field',$goods);
		$this->assign('currentAttr',$currentAttr);
		$this->assign('attrClass',$attrClass);
		$this->display('content.html');
	}
	// 检测选择的商品库存存在吗
	public function HasStock(){
		$gid = Q('gid',0,'intval');
		$avid=Q('avid');
		// avid(0-9)拆成数组
		// echo $avid;exit;
		$avid = explode('_',$avid);

		if($this->getStockId($gid,$avid)){
			echo 1;exit;
		}else{
			echo 0;exit;
		}
		
	}
	//组写sql语句查找库存是否存在
	public function getStockId($gid,$avid){
		$pre =C('DB_PREFIX');
		$JOIN='';
		foreach ($avid as $i => $id) {
			$as="a{$i}";
			$JOIN.="{$pre}stock_attr AS $as JOIN "; 
		}
		$JOIN=substr($JOIN,0,-5);
		$ON=' ON ';
		for($i=0;$i<count($avid)-1;$i++){
			$as ="a{$i}";
			$rAs="a".($i+1);
			$ON.="{$as}.stid={$rAs}.stid AND ";
		}
		$ON=substr($ON,0,-4);
		$WHERE=' WHERE ';
		foreach ($avid as $i => $id) {
			$as="a{$i}";
			$WHERE.= "{$as}.avid=$id AND ";
		}
		$WHERE.=" $as.gid=$gid";
		$SQL = "SELECT a0.stid FROM ".$JOIN.$ON.$WHERE;
		$result=M()->query($SQL);
		return $result?$result[0]['stid']:null;
	}
	
	//用户最近浏览
	private function browse($gid){
		$_SESSION['browse'][$gid]=$gid;
	}

	//留言
	public function leave($gid=null){
		$massage=M('massage')->where("gid=$gid")->all();
	
		if(!empty($massage)){
			foreach($massage as $v){
			$uid=$v['uid'];
			$SQL="SELECT * FROM hd_g_massage AS m JOIN hd_g_user AS u ON m.uid=u.uid WHERE  m.gid={$gid}";
			$data=M()->query($SQL);
			}
			$this->assign('massage',$data);
		}else{
			return false;
		}

		
		
		
	}












	protected function display($tplFile = null, $cacheTime = null, $cachePath = null, $stat = false, $contentType = "text/html", $charset = "", $show = true)
    {
       $tplFile=C('TPL_PATH').C('TPL_STYLE').'/'.$tplFile;
		parent::display($tplFile);
    }










}



 ?>